package com.springboot_shopping.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot_shopping.Mapper.UserMapper;
import com.springboot_shopping.entity.User;
import com.springboot_shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    //1、注册
    @Override
    public boolean register(User user) {
        // 验证注册信息是否完整
        if (StringUtils.isEmpty(user.getUserName()) ||
                StringUtils.isEmpty(user.getPassword()) ||
                StringUtils.isEmpty(user.getEmail()) ||
                StringUtils.isEmpty(user.getPhone())) {
            return false;
        }

        // 检查手机号是否已注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_phone", user.getPhone());
        List<User> userList = userMapper.selectList(queryWrapper);
        if (!userList.isEmpty()) {
            return false; // 手机号已存在
        }

        // 设置注册时间和会员类型
        user.setRegisterTime(new Date());
        user.setUType(3);

        // 插入用户数据
        int result = userMapper.insert(user);
        return result > 0;
    }
//2、登录
    @Override
    public User login(String phone, String password) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
            return null;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_phone", phone)
                .eq("u_password", password);
        return userMapper.selectOne(queryWrapper);
    }
//3、查询用户（根据手机号）
    @Override
    public User findByPhone(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return null;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_phone", phone);
        return userMapper.selectOne(queryWrapper);
    }
}